package com.my.webflux;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;
import java.util.concurrent.Flow;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/2/18 10:44
 */
public class FluxMainApplication {

    public static void main(String[] args) throws IOException {
        // 快速自己编写一个能处理请求的服务器
        
        // 1.创建一个能处理Http请求的处理器
        // Mono<void> 发布一个型号
        HttpHandler handler = (request, response) -> {
            // 编写请求处理的业务，给浏览器写一个内容
            System.out.println(request.getRemoteAddress() + "发起请求");
            
            /*response.getHeaders(); // 获取响应头
            response.getCookies(); // 获取cookie
            response.getStatusCode(); // 获取响应状态码
            response.bufferFactory(); // buffer工厂
            response.writeWith(); // 把xxx写出去
            // 响应结束
            response.setComplete();
            
            response.writeAndFlushWith();*/
            
            // 数据的发布者：Mono<DataBuffer> Flux<DataBuffer>
            
            // 创建响应数据的DataBuffer
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            
            // 数据Buffer
            DataBuffer dataBuffer = dataBufferFactory.wrap((new String(request.getURI().toString()) + "==>hello").getBytes());
            
            // 需要一个 DataBuffer的发布者
            Mono<DataBuffer> mono = Mono.just(dataBuffer);
            
            
            return response.writeWith(mono);
        };
        
        // 2.启动有个服务器，监听8080端口，接收数据，拿到数据交给 HttpHandler 进行请求处理

        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
        
        // 3.启动HttpServer
        HttpServer.create()
                .host("localhost")
                .port(8080)
                .handle(adapter)
                .bindNow(); // 现在绑定

        System.out.println("服务器启动完成....监听8080，接收请求");
        System.in.read();
        System.out.println("服务器停止");
    }
    
}
